package org.jeecg.modules.system.service.impl;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.IpUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.system.service.IRescenterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 资源中心服务
 * @Author: heiyexinkong
 * @Date: 2024-01-10
 * @Version: V1.0
 */
@Service
public class RescenterServiceImpl implements IRescenterService {

    private static Logger logger = LoggerFactory.getLogger(RescenterServiceImpl.class);
    /**
     * 资源中心baseUrl
     */
    @Value("${rescenter.baseUrl}")
    private String baseUrl;


    public Result<String> userLogin(String userName, String password) {
        try{
//            String url = "http://cmp.changan.com/rescenter/rest/resRestApi/v2" + "/userLogin";
            String url = baseUrl + "/userLogin";
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            //请求参数转JOSN字符串
            Map<String,String> param = new HashMap<>();
            param.put("loginId",userName);
            param.put("password",password);
            String ip = "";
            try {
                //获取request
                HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
                //获取IP地址
                ip = IpUtils.getIpAddr(request);
            } catch (Exception e) {
                ip = "127.0.0.1";
            }
            param.put("clientIP",ip);
            List<NameValuePair> paramList=new ArrayList<NameValuePair>();
            for(Map.Entry<String, String> entry : param.entrySet()){
                paramList.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(paramList,"UTF-8"));

            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                com.alibaba.fastjson.JSONObject result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
                if ("200".equals(result.get("result"))) {
                    com.alibaba.fastjson.JSONObject data =JSON.parseObject(result.get("data").toString());
                    String token  = (String) data.get("msg");
                    if(StringUtils.isNotBlank(token)){
                        return Result.ok(token);
                    }
                }
            }
        }catch (Exception e){
            logger.error("userLogin失败："+e.getMessage());
            return Result.error("登录资源中心失败，请检查用户名密码是否正确！");
        }

        return Result.error("登录资源中心失败，请检查用户名密码是否正确！");
    }

}
